package pers.youqu.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import pers.youqu.common.exception.YqException;
import pers.youqu.user.dto.UserDTO;
import pers.youqu.user.po.User;
import pers.youqu.user.service.UserService;

import java.util.stream.Collectors;

/**
 * @author Jason
 * @version 1.0.0
 * @date 2020/12/16 14:21
 * @Description TODO
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 判断信息是否存在
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/info/exists/{data}/{type}")
    public ResponseEntity<Boolean> isExists(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.isExists(data, type));
    }

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @PostMapping("/info/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone) {
        userService.sendCode(phone);
        return ResponseEntity.status(200).build();
    }

    /**
     * 注册
     * @param user
     * @param bindingResult
     * @param code
     * @return
     */
    @PostMapping("/info")
    public ResponseEntity<Void> registerUser(User user, BindingResult bindingResult, @RequestParam("code") String code) {
        if (bindingResult.hasErrors()) {
            String msg = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new YqException(400, msg);
        }
        userService.registerUser(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    /**
     * 根据用户名和密码查询
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/info")
    public ResponseEntity<UserDTO> findUserByUsernameAndPassword(
            @RequestParam("username") String username, @RequestParam("password") String password) {
        return ResponseEntity.ok(userService.findUserByUsernameAndPassword(username, password));
    }
}
